package com.yyk.yiliao.ui.activity.shopcart;


import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ocnyang.cartlayout.RecyclerViewWithContextMenu;
import com.ocnyang.cartlayout.bean.CartItemBean;
import com.ocnyang.cartlayout.bean.ICartItem;
import com.ocnyang.cartlayout.listener.CartOnCheckChangeListener;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.logger.Logger;
import com.yyk.yiliao.R;
import com.yyk.yiliao.base.BaseActivity;
import com.yyk.yiliao.ui.activity.detail.activity.Detail_Activity;
import com.yyk.yiliao.ui.activity.detail.activity.PlaceOrder_Activity;
import com.yyk.yiliao.bean.CartCartpay_Info;
import com.yyk.yiliao.util.Md5Util2;
import com.yyk.yiliao.util.ToastUtil;
import com.yyk.yiliao.util.rx.ApiService;
import com.yyk.yiliao.util.rx.RxUtils;
import com.yyk.yiliao.bean.CartCartlist_Info;
import com.yyk.yiliao.bean.CartDelcart_Info;
import com.yyk.yiliao.bean.CartOpcart_Info;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class ShopCart_Activity extends BaseActivity {
    public static ShopCart_Activity intanse;
    @BindView(R.id.ll_null) //空背景图
            LinearLayout llNull;
    @BindView(R.id.tv_title) //toolbar 标题
            TextView mTvTitle;
    @BindView(R.id.tv_edit) //toolbar 编辑
            TextView mTvEdit;
    @BindView(R.id.toolbar) //toolbar
            Toolbar toolbar;
    @BindView(R.id.recycler)  //recyclerview +选项功能
            RecyclerViewWithContextMenu recyclerView;
    @BindView(R.id.checkbox_all)//全选
            CheckBox mCheckBoxAll;
    @BindView(R.id.tv_total_price) //总计------价格
            TextView mTvTotal;
    @BindView(R.id.bottom_ll) //总计多少钱
            LinearLayout mBootomll;
    @BindView(R.id.btn_go_to_pay) //结算 支付
            TextView mBtnSubmit;
    @BindView(R.id.bottom_rl) //底部框子
            RelativeLayout mBootomrl;

    private ShopCart_Adapter mAdapter; //购物车适配器
    private boolean isEditing;//是否处于编辑状态
    private int totalCount;//购物车商品ChildItem的总数量，店铺条目不计算在内
    private int totalCheckedCount;//勾选的商品总数量，店铺条目不计算在内
    private double totalPrice;//勾选的商品总价格
    private String result; //删除购物车 ID
    private String result2;//结算购物车ID

    final ArrayList<CartItemBean> cartItemBeans = new ArrayList<>();


    @Override
    public int getLayoutId() {
        return R.layout.activity_shopcart;
    }

    @Override
    public void initView() {
        initToolbar();
    }

    private void initToolbar() {
        hidetoolBar();
        final Drawable upArrow = getResources().getDrawable(R.mipmap.icon_shangp_fh);
        toolbar.setNavigationIcon(upArrow);
        //设置返回按钮的点击事件
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void initData() {
        intanse = this;
//        EventBus.getDefault().register(this);
        mTvTitle.setText(getString(R.string.cart, 0));
        mBtnSubmit.setText(getString(R.string.go_settle_X, 0));
        mTvTotal.setText(getString(R.string.rmb_X, 0.00));
        //        // 给列表注册 ContextMenu 事件。
        //        // 同时如果想让ItemView响应长按弹出菜单，需要在item xml布局中设置 android:longClickable="true"
        //        registerForContextMenu(recyclerView);
        //        recyclerView.setLayoutManager(new LinearLayoutManager(ShopCart_Activity.this));
        //        mAdapter = new ShopCart_Adapter(ShopCart_Activity.this, getData());
        //        mAdapter.setOnCheckChangeListener(new CartOnCheckChangeListener(recyclerView, mAdapter) {
        //            @Override
        //            public void onCalculateChanged(ICartItem cartItemBean) {
        //                calculate();
        //            }
        //        });
        //        recyclerView.setAdapter(mAdapter);
        initAdapter();
    }


    @Override
    protected void onResume() {
        super.onResume();
        //刷新数据并且删除选中的条目
        initShopCart(true);
        mAdapter.removeChecked();
    }


    private void initAdapter() {
        recyclerView.setLayoutManager(new LinearLayoutManager(ShopCart_Activity.this));
        mAdapter = new ShopCart_Adapter(ShopCart_Activity.this, cartItemBeans);
        mAdapter.setOnCheckChangeListener(new CartOnCheckChangeListener(recyclerView, mAdapter) {
            @Override
            public void onCalculateChanged(ICartItem cartItemBean) {
                calculate();
            }

        });

        mAdapter.setOnListenr(new ShopCart_Adapter.onListenr() {

            @Override
            public void onClickAddDelete(int num, int poston) {
                Map<String, String> map = new TreeMap<>();
                map.put("uid", Hawk.get("uid", 0) + "");
                long itemId = ((GoodsBean) cartItemBeans.get(poston)).getItemId();
                map.put("gid", itemId + "");
                Logger.e("购物车 gid" + " ___" + itemId);
                map.put("num", num + "");
                map.put("sign", Md5Util2.createSign(map));
                initNumberAddDelete(map, null);
            }

            @Override
            public void onClickItem(int id) {
                Bundle bundle = new Bundle();
                bundle.putInt("id", id);
                startAct(Detail_Activity.class, bundle);
            }

        });
        recyclerView.setAdapter(mAdapter);
    }

    /**
     * 批量修改购物车数量
     *
     * @param map
     * @param num
     */
    private void initNumberAddDelete(Map<String, String> map, String num) {

        RxUtils.getInstance().retrofit.create(ApiService.class).postCartOpcart(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartOpcart_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();

                    }

                    @Override
                    public void onNext(CartOpcart_Info info) {
                        Logger.e("购物车批量修改购" + info.getCode());
                        if (info.getCode() == 1) {
                            calculate();
                        } else if (info.getCode() == 101) {
                            ToastUtil.showShort(ShopCart_Activity.this, "没有该商品 ");
                        } else if (info.getCode() == 102) {
                            ToastUtil.showShort(ShopCart_Activity.this, "插入失败 ");
                        } else if (info.getCode() == 103) {
                            ToastUtil.showShort(ShopCart_Activity.this, "购物车已存在 ");
                        } else if (info.getCode() == 104) {
                            ToastUtil.showShort(ShopCart_Activity.this, "商品数量修改失败 ");
                        } else {
                            ToastUtil.showShort(ShopCart_Activity.this, "商品删除失败 ");
                        }

                    }


                });

    }

    /**
     * 删除物品
     */
    private void initNumberDelete(String gid) {
        Map<String, String> map = new TreeMap<>();
        map.put("uid", Hawk.get("uid", 0) + "");
        map.put("gid", gid + "");
        map.put("sign", Md5Util2.createSign(map));
        Logger.e("购物车 删除gid" + " ___" + gid);
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartDelcart(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartDelcart_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();


                    }

                    @Override
                    public void onNext(CartDelcart_Info info) {
                        Logger.e("购物车删除" + info.getCode());
                        if (info.getCode() == 1) {
                            ToastUtil.showShort(ShopCart_Activity.this, "删除成功");
                            initShopCart(true);
                            mAdapter.removeChecked();
                        } else if (info.getCode() == 101) {
                            ToastUtil.showShort(ShopCart_Activity.this, "没有该商品 ");
                        } else if (info.getCode() == 102) {
                            ToastUtil.showShort(ShopCart_Activity.this, "插入失败 ");
                        } else if (info.getCode() == 103) {
                            ToastUtil.showShort(ShopCart_Activity.this, "购物车已存在 ");
                        } else if (info.getCode() == 104) {
                            ToastUtil.showShort(ShopCart_Activity.this, "商品数量修改失败 ");
                        } else {
                            ToastUtil.showShort(ShopCart_Activity.this, "商品删除失败 ");
                        }

                    }


                });

    }


    /**
     * 数据初始化尤其重要
     * 1. childItem 数据全部在 GroupItem 数据的下方，数据顺序严格按照对应关系；
     * 2. GroupItem 下的 ChildItem 数据不能为空；
     * 3. 初始化时如果不需要，所有类型的条目都可以不设置ID，GroupItem也不用设置setChilds()；
     * <p>
     * 列表操作时数据动态的变化设置：
     * 1. 通过 CartAdapter 的 addData、setNewData；
     * 2. 单个添加各个条目可以通过对应的 add 方法；
     * 3. 单独添加一个 GroupItem ,可以把它的 ChildItem 数据放到 setChilds 中。
     *
     * @return
     */
    private void initShopCart(final boolean flag) {
        Map<String, String> map = new TreeMap<>();

        map.put("uid", Hawk.get("uid", 0) + "");
        map.put("sign", Md5Util2.createSign(map));
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartCartlist(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())
                .subscribe(new Subscriber<CartCartlist_Info>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
//                        Logger.e("购物车列表异常" + e.toString());
                        recyclerView.setVisibility(View.GONE);
                        llNull.setVisibility(View.VISIBLE);
                        mAdapter.notifyDataSetChanged();

                    }

                    @Override
                    public void onNext(CartCartlist_Info cartCartlist_info) {
                        Logger.e("购物车列表" + cartCartlist_info.toString());

                        if (cartCartlist_info.getData() == null) {
                            Logger.e("购物车列表2");
                            recyclerView.setVisibility(View.GONE);
                            llNull.setVisibility(View.VISIBLE);
                            mAdapter.notifyDataSetChanged();
                        } else {
                            Logger.e("购物车列表222");
                            if (cartCartlist_info.getCode() == 1) {
                                List<CartCartlist_Info.DataBean> data = cartCartlist_info.getData();
                                if (flag) {
                                    cartItemBeans.clear();
                                }
                                if (cartCartlist_info.getData() != null && cartCartlist_info.getData().size() > 0) {
                                    recyclerView.setVisibility(View.VISIBLE);
                                    llNull.setVisibility(View.GONE);

                                    NormalBean normalBean = new NormalBean();
                                    normalBean.setMarkdownNumber(6);
                                    cartItemBeans.add(normalBean);
                                    for (int i = 0; i < data.size(); i++) {
                                        ShopBean shopBean = new ShopBean();
                                        String sname = data.get(i).getSname();
                                        shopBean.setShop_name(sname);
                                        shopBean.setItemType(CartItemBean.TYPE_GROUP);
                                        cartItemBeans.add(shopBean);
                                        List<CartCartlist_Info.DataBean.GoodslistBean> goodslist = data.get(i).getGoodslist();
                                        for (int j = 0; j < goodslist.size(); j++) {
                                            GoodsBean goodsBean = new GoodsBean();
                                            goodsBean.setItemType(CartItemBean.TYPE_CHILD);
                                            goodsBean.setGoods_name(goodslist.get(j).getName());//名称
                                            goodsBean.setGoods_price(goodslist.get(j).getMoney()); //价钱
                                            goodsBean.setGoods_amount(goodslist.get(j).getNum()); //数量
                                            goodsBean.setImg(goodslist.get(j).getImg());//图片
                                            goodsBean.setItemId(goodslist.get(j).getOid()); //商品id
                                            goodsBean.setCartid(goodslist.get(j).getCartid()); //购物车Id

                                            goodsBean.setGroupId(i);
                                            cartItemBeans.add(goodsBean);
                                        }
                                    }
                                    Logger.e("ZKK" + cartItemBeans.size());
                                }
                                mAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
    }


    /**
     * 统计操作<br>
     * 1.先清空全局计数器<br>
     * 2.遍历所有子元素，只要是被选中状态的，就进行相关的计算操作<br>
     * 3.给相关的 textView 进行数据填充
     */
    @SuppressLint("ResourceAsColor")
    private void calculate() {
        totalCheckedCount = 0;
        totalCount = 0;
        totalPrice = 0.00;
        int notChildTotalCount = 0;
        StringBuffer options = new StringBuffer();

        StringBuffer options2 = new StringBuffer();
      /*
        * 在这获取选中的 checkbox 的id， 并记录保存
        */
        if (mAdapter.getData() != null) {
            for (ICartItem iCartItem : mAdapter.getData()) {
                if (iCartItem.getItemType() == ICartItem.TYPE_CHILD) {
                    totalCount++;
                    if (iCartItem.isChecked()) {
                        totalCheckedCount++;
                        totalPrice += ((GoodsBean) iCartItem).getGoods_price() * ((GoodsBean) iCartItem).getGoods_amount();

                        int itemId = (int) ((GoodsBean) iCartItem).getItemId();
                        options.append(itemId);
                        options.append(",");


                        //购物结算 id
                        int cartid = ((GoodsBean) iCartItem).getCartid();
                        options2.append(cartid);
                        options2.append(",");
                    }
                } else {
                    notChildTotalCount++;
                }
            }
        }

        result = options.toString();
        //        result = string.replace("0,", "").replace("0", "");
        Logger.e("选择id——" + result);


        //购物结算需要的购物车 id
        result2 = options2.toString();
        Logger.e("选择id2——" + result2);


        mTvTitle.setText(
                getString(R.string.cart, totalCheckedCount));
        mBtnSubmit.setText(
                getString(isEditing ? R.string.delete_X : R.string.go_settle_X, totalCheckedCount));

        mTvTotal.setText(

                getString(R.string.rmb_X, totalPrice));
        if (mCheckBoxAll.isChecked() && (totalCheckedCount == 0 || (totalCheckedCount + notChildTotalCount) != mAdapter.getData().

                size()))

        {
            mCheckBoxAll.setChecked(false);
        }
        if (totalCheckedCount != 0 && (!mCheckBoxAll.isChecked()) && (totalCheckedCount + notChildTotalCount) == mAdapter.getData().

                size())

        {
            mCheckBoxAll.setChecked(true);
        }


    }


    @OnClick({R.id.tv_edit, R.id.btn_go_to_pay, R.id.checkbox_all})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            //编辑按钮事件
            case R.id.tv_edit:
                isEditing = !isEditing;
                mTvEdit.setText(getString(isEditing ? R.string.edit_done : R.string.edit));
//                mTvTitle.setText(R.string.cart,totalCount);
                mBootomll.setVisibility(isEditing ? View.GONE : View.VISIBLE);
                mBootomrl.setBackgroundResource(isEditing ? R.mipmap.img_gwc_dbbj : R.mipmap.img_gwc_dbbj);
                mBtnSubmit.setText(getString(isEditing ? R.string.delete_X : R.string.go_settle_X, totalCheckedCount));
                mBtnSubmit.setTextColor(isEditing ? Color.parseColor("#ffffff") : Color.parseColor("#ffffff"));
                break;
            //提交订单 & 删除选中（编辑状态）
            case R.id.btn_go_to_pay:
                submitEvent();
                break;
            case R.id.checkbox_all:
                if (mAdapter == null) {
                } else {
                    mAdapter.checkedAll(((CheckBox) view).isChecked());
                }
                break;
        }
    }

    private void submitEvent() {
        if (isEditing) {
            if (totalCheckedCount == 0) {
                Toast.makeText(this, "请勾选你要删除的商品", Toast.LENGTH_SHORT).show();
            } else {
                initNumberDelete(result);
            }

        } else {
            if (totalCheckedCount == 0) {
                Toast.makeText(this, "你还没有选择任何商品", Toast.LENGTH_SHORT).show();
            } else {
                initShopSetllement(result2);
//                Toast.makeText(this,
//                        new StringBuilder().append("你选择了").append(totalCheckedCount).append("件商品")
//                                .append("共计 ").append(totalPrice).append("元"),
//                        Toast.LENGTH_SHORT).show();
            }

        }
        return;
    }

    /**
     * 商品结算
     */
    private void initShopSetllement(String ids) {
        Map<String, String> map = new TreeMap<>();

        map.put("ids", ids + "");
        map.put("sign", Md5Util2.createSign(map));
        Logger.e("购物车 结算ids" + " ___" + ids);
        RxUtils.getInstance().retrofit.create(ApiService.class).postCartCartpay(map)
                .subscribeOn(Schedulers.io())     //调度线程
                .observeOn(AndroidSchedulers.mainThread())
                .unsubscribeOn(Schedulers.io())   //取消订阅
                .subscribe(new Subscriber<CartCartpay_Info>() {

                    @Override
                    public void onCompleted() {
                        //完成的时候调用

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();


                    }

                    @Override
                    public void onNext(CartCartpay_Info info) {
                        Logger.e("购物车结算" + info.toString());
                        if (info.getCode() == 1) {
                            info.setSub_type(1);
                            EventBus.getDefault().postSticky(info);
                            startAct(PlaceOrder_Activity.class);
                        } else if (info.getCode() == 106) {
                            ToastUtil.showShort(ShopCart_Activity.this, "没有找到结算商品 ");
                        }
                    }


                });

    }


}
